"use strict"

var uuid = require("uuid")

var WebSocket = require("ws");

const WebSocketServe = WebSocket.Server;

const wss = new WebSocketServe({
    port:8080
});

/**
 * @type {id}
 */
let onlineUser = {};

wss.on("connection",function(ws){
    let selfUUID = uuid.v4();
    onlineUser[selfUUID] = ws;
    let allUuids = Object.getOwnPropertyNames(onlineUser);
    allUuids.forEach(userUuid=>{
        if(selfUUID === userUuid){
            return;
        }
        onlineUser[userUuid].send(JSON.stringify({
            msg_type:"newOnlineList",
            newOnline:selfUUID
        }),function(err){
            console.log(err);
        });
    });
    ws.send(JSON.stringify({msg_type:"onlineList",onlineList:allUuids}),(err)=>{
        console.log(err)
    });
    ws.on("message",function(message){
        console.log(`[SERVER] Received: ${message}`);
        user.forEach((userLink)=>{
            userLink.send({},(err)=>{
                if(err){
                    console.log(`[SERVER] error: ${err}`);
                }
            });
        });
    });
    ws.on("close",function(message){
        delete onlineUser[selfUUID];
        Object.getOwnPropertyNames(onlineUser).forEach(thisUUid=>{
            onlineUser[thisUUid].send(JSON.stringify({msg_type:"deleteLink",uuid:selfUUID}),(err)=>{
                console.log(err)
            });
        })
    });
});